package com.future.common.base;

import java.text.SimpleDateFormat;

import javax.servlet.http.HttpServletRequest;

import com.future.common.exception.AppException;
import com.jfinal.core.ActionException;
import com.jfinal.core.Controller;
import com.jfinal.kit.HttpKit;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.StrKit;
import com.jfinal.render.RenderManager;
import com.jfinal.validate.Validator;

public abstract class BaseValidator extends Validator {
	protected String error_key = "error_key";
	private static final RenderManager renderManager = RenderManager.me();
	/**
	 * 有校验失败就返回
	 */
	public BaseValidator() {
		setShortCircuit(true);
	}
	/**
	 * 获取request
	 * @return
	 */
	protected HttpServletRequest getRequest() {
		return getController().getRequest();
	}
	
	/**
	 * 获取json body
	 * @param type
	 * @return
	 */
	protected <T> T getJsonBody(Class<T> type) {
		String jsonStr = HttpKit.readData(getRequest());
		T result = JsonKit.parse(jsonStr, type);
		return result;
	}
	
	/**
	 * 获取para值
	 * @param name
	 * @return
	 */
	protected String getPara(String name) {
		return getRequest().getParameter(name);
		
	} 
	
	@Override
	protected void handleError(Controller c) {
		if(!StrKit.isBlank(c.getAttr(error_key))){
			throw new AppException(c.getAttr(error_key));
		}
	}
	
	protected void validateRequiredString(String field, String errorMessage) {
		if (StrKit.isBlank(controller.getPara(field))) {
			addError(error_key, errorMessage);
		}
	}
	
	protected void addError(String errorMessage) {
		addError(error_key, errorMessage);
	}
	
	protected boolean isDate(String value) {
		return this.isDate(value, "yyyy-MM-dd");
	}
	protected boolean isDateTime(String value) {
		return this.isDate(value, "yyyy-MM-dd hh:mm:ss");
	}
	protected boolean isDate(String value, String formate) {
		try {
			new SimpleDateFormat(formate).parse(getPara(value));
		} catch (Exception e) {
			return false;
		}
		return true;
	}
	
	public Integer getParaToInt(String name) {
		return toInt(getPara(name), null);
	}
	
	private Integer toInt(String value, Integer defaultValue) {
		try {
			if (StrKit.isBlank(value))
				return defaultValue;
			value = value.trim();
			if (value.startsWith("N") || value.startsWith("n"))
				return -Integer.parseInt(value.substring(1));
			return Integer.parseInt(value);
		}
		catch (Exception e) {
			throw new ActionException(400, renderManager.getRenderFactory().getErrorRender(400),  "Can not parse the parameter \"" + value + "\" to Integer value.");
		}
	}
}
